﻿using System;
using System.Collections.Generic;
using System.Device.Location;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace Indt.Components
{
    public class Geolocation
    {
        private GeoCoordinateWatcher watcher;
        public string Status { get; set; }
        public string Latitude { get; private set; }
        public string Longitude { get; private set; }

        public Geolocation() 
        {
            watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
            watcher.MovementThreshold = 20;

            watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(StatusChanged);
            watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(PositionChanged);

            watcher.Start();        
        }

        void StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            Debug.WriteLine("Status Changed");

            switch (e.Status)
            {
                case GeoPositionStatus.Disabled:
                    Status = "location is unsupported on this device";
                    break;
                case GeoPositionStatus.Initializing:
                    Status = "initializing location service";
                    break;
                case GeoPositionStatus.NoData:
                    Status = "data unavailable";
                    break;
                case GeoPositionStatus.Ready:
                    Status = "receiving data";
                    break;
            }
        }


        void PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            Debug.WriteLine("Position Changed");
            Latitude = Convert.ToSingle(e.Position.Location.Latitude.ToString()).ToString();
            Longitude = e.Position.Location.Longitude.ToString();
        }

        public string ConvertDegrees(double coord, string ponto)
        {
            char vPont;
 
            if (ponto == "lat")
            {
                vPont = coord < 0 ? 'S' : 'N';
            }else {
                vPont = coord < 0 ? 'W' : 'E';
            }

           int sec = (int)Math.Round(coord * 3600);
           int deg = sec / 3600;
           sec = Math.Abs(sec % 3600);
           int min = sec / 60;
           sec %= 60;

            if(deg < 0){
                deg = 0 - deg; 
            }

           string value = deg + "°" + min + "'" + sec + '"' + vPont;

           return value;
       }
    }
}
